/*
 * 版权所有 (C) 2018 知启蒙(ZHIQIM) 保留所有权利。
 * 
 * 欢迎到知启蒙网站（https://www.zhiqim.com）购买正版软件，知启蒙还提供许多开源框架和软件。
 * 
 * 1、本软件产品所有源代码受《中华人民共和国著作权法》和其他有关法律、法规的保护，其所有知识产权归湖南知启蒙科技有限公司所有；
 * 2、禁止复制和修改。不得复制修改、翻译或改编本软件所有源代码，或者基于本软件产品创作衍生作品；
 * 3、禁止进行逆向工程。不得对本软件的源代码进行逆向工程、反编译或试图以其他方式发现软件的源代码；
 * 4、个别授权：如需进行商业性的销售、复制、分发，包括但不限于软件销售、预装、捆绑等，必须获得知启蒙的书面授权和许可；
 * 5、保留权利：本注释未明示授权的其他一切权利仍归知启蒙所有，任何人使用其他权利时必须获得知启蒙的书面同意。
 */
package net.redxyz.repost.resource;

import java.sql.SQLException;
import java.util.List;

import net.redxyz.repost.resource.model.SellerCatRoot;
import net.redxyz.repost.service.dao.ArticleDao;
import net.redxyz.repost.service.dao.PermissionDao;
import net.redxyz.repost.service.dao.SysParamDao;
import net.redxyz.top.TaobaoService;
import net.redxyz.top.dbo.sys.SysArticle;
import net.redxyz.top.dbo.sys.SysPermission;
import net.redxyz.top.dbo.sys.SysPopup;
import net.redxyz.top.dbo.user.User;

import org.zhiqim.httpd.HttpSessionUser;
import org.zhiqim.kernel.Global;
import org.zhiqim.kernel.annotation.AnAlias;
import org.zhiqim.kernel.util.DateTimes;
import org.zhiqim.kernel.util.Strings;
import org.zhiqim.kernel.util.Validates;
import org.zhiqim.orm.ORM;
import org.zhiqim.orm.ORMException;
import org.zhiqim.orm.dbo.Selector;

/**
 * 用户会话信息
 *
 * @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
 */
@AnAlias("SessionUser")
public class SessionUser extends HttpSessionUser
{
    private static final SessionUserService service = new SessionUserService();
    public static final String modify_key = "__isModify__"; // 是否需要服务端更新
    
    //客户信息
    private User user;
    private SellerCatRoot seRoot;
    
    //子账号信息
    private String subNick;
    private String subSessionId;
    private String subSessionTime;
    private int subExpiresIn;
    private int subExpiresInW2;
    private String openUid;
    
    //低版本赠送高版本
    private boolean isGift;
    private int giftVersionNo;
    private String giftStartDate;
    private String giftEndDate;
    
    //用户会话控制信息
    private boolean isAdmin;
    private boolean isUpdateData;
    private boolean isCloseTopNotice;
    private boolean isClosePopup;
    private SysPopup popup;//符合弹出窗口的条件

    //终端来源
    private int from = 0; //0,1,2 对应web pc mobile三种 默认为web
    
    private boolean hasSubNick;//是否子账号登陆
    
    // 是否为 应用接入APP 的用户
    private long open_app_key;// 当前通过那个appKey 登录
    /***********************************************/
    //以下为获取方法
    /***********************************************/
    
    public String getSessionName()
    {
        return subNick==null?user.getNick():subNick;
    }
    
    public String getOpenUid() {
        if(openUid == null && user != null) {
            return user.getOpenUid();
        }
        return openUid;
    }

    public void setOpenUid(String openUid) {
        this.openUid = openUid;
    }

    public String getSessionKey()
    {
        return super.getSessionId();
    }

    public String getLoginTime()
    {
        return super.getCreateTime();
    }
    
    public int getRemainMinute(int sessionTimeout)
    {
        long remain = System.currentTimeMillis() - super.getLastAccessed();
        return (int)(sessionTimeout - remain / 1000) / 60;
    }
    
    /**返回 　*天*小时*分 */
    public static String getRemainDayStr(String time)
    {
        // 获得两个时间的秒时间差异
        int diff = DateTimes.compareSecond(time, DateTimes.getDateTimeString());
        if(diff <= 0)
            return "-- --";
        
        long nd = 24 * 60 * 60;
        long nh = 60 * 60;
        long nm = 60;

        // 计算差多少天
        long day = diff / nd;
        
        // 计算差多少小时
        long hour = diff % nd / nh;
        
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm;
        
        return day + "天" + hour + "小时" + min + "分钟";
    }
    
    /**返回　*小时*分*秒 */
    public static String getRemainHourStr(String time)
    {
        // 获得两个时间的秒时间差异
        int diff = DateTimes.compareSecond(time, DateTimes.getDateTimeString());
        
        if(diff <= 0)
            return "-- --";
        
        long nd = 60 * 60;
        long nh = 60;
        
        // 计算差多少小时
        long hour = diff / nd;
        
        // 计算差多少分钟
        long min = diff % nd / nh;
        
        // 计算差多少秒//输出结果
        long sec = diff % nd % nh;
        
        return hour + "小时" + min + "分钟" + sec + "秒";
    }
    
    public String getNickLogined()
    {
        if (hasSubNick)
            return subNick;
        
        return user.getNick();
    }

    public String getSessionId()
    {
        if (hasSubNick)
            return subSessionId;
        
        return user.getSessionId();
    }
    
    public long getUserId()
    {
        return Long.parseLong(user.getUserId());
    }

    public String getSessionTime()
    {
        if (hasSubNick)
            return subSessionTime;
        
        return user.getSessionTime();
    }

    public int getExpiresIn()
    {
        if (hasSubNick)
            return subExpiresIn;
        
        return user.getExpiresIn();
    }
    
    public int getExpiresInW2()
    {
        if (hasSubNick)
            return subExpiresInW2;
        
        return user.getExpiresInW2();
    }
    
    public long getUserPoint()
    {
        return user.getUserPoint();
    }
    
    /** 以下为客户在非凡掌柜信息 */
    public User getUser()
    {
        return user;
    }
    
    public void setUser(User user)
    {
        this.user = user;
    }

    public String getNick()
    {
        return user.getNick();
    }
    
    public int getUserSmsNum()
    {
        return user.getUserSmsNum();
    }
    
    public int getUserMailNum()
    {
        return user.getUserSmsNum();
    }
    
    public void setItemNum(int itemNum)
    {
        this.user.setItemNum(itemNum);
    }

    public int getItemNum()
    {
        return user.getItemNum();
    }

    public String getCreateTime()
    {
        return user.getCreateTime();
    }

    public String getLastLoginTime()
    {
        return user.getLastLoginTime();
    }

    public void setVersionNo(int versionNo)
    {
        this.user.setVersionNo(versionNo);
    }

    public int getVersionNo()
    {
        return user.getVersionNo();
    }

    public void setStartDate(String startDate)
    {
        this.user.setStartDate(startDate);
    }

    public String getStartDate()
    {
        return user.getStartDate();
    }

    public void setEndDate(String endDate)
    {
        this.user.setEndDate(endDate);
    }

    public String getEndDate()
    {
        if (Validates.isNotEmpty(user.getEndDate()))
            return user.getEndDate();
        else
            return getExpireInTime().substring(0, 10);
    }

    public void setEmail(String email)
    {
        this.user.setEmail(email);
    }

    public String getEmail()
    {
        return user.getEmail();
    }

    public void setMobile(String mobile)
    {
        this.user.setMobile(mobile);
    }

    public String getMobile()
    {
        return user.getMobile();
    }

    public String getType()
    {
        return user.getType();
    }
    
    public boolean isTypeC()
    {
        return "C".equals(user.getType());
    }
    
    public boolean isTypeB()
    {
        return "B".equals(user.getType());
    }
    
    public boolean isAutoRepostLimited()
    {
        return user.getAutoRepostLimited() == 1;
    }
    
    public String getBirthday()
    {
        return user.getBirthday();
    }
    
    public String getAvatar()
    {
        return user.getAvatar();
    }
    
    public int getShopId()
    {
        return user.getShopId();
    }
    
    public String getShopTitle()
    {
        return user.getShopTitle();
    }
    
    public String getShopTitle20()
    {
        String title = user.getShopTitle();
        if (Validates.isByteLen(title, 0, 14))
            return title;
        return Strings.substringLen(title, 14);
    }
    
    public int getLevel()
    {
        return user.getLevel();
    }
    
    public boolean isGift()
    {
        return isGift;
    }

    public void setGift(boolean isGift)
    {
        this.isGift = isGift;
    }
    
    public int getGiftVersionNo()
    {
        if (isGift)
            return giftVersionNo;
        else
            return user.getVersionNo();
    }

    public void setGiftVersionNo(int giftVersionNo)
    {
        this.giftVersionNo = giftVersionNo;
    }

    public String getGiftStartDate()
    {
        if (isGift)
            return giftStartDate;
        else
            return getStartDate();
    }

    public void setGiftStartDate(String giftStartDate)
    {
        this.giftStartDate = giftStartDate;
    }

    public String getGiftEndDate()
    {
        if (isGift)
            return giftEndDate;
        else
            return getEndDate();
    }
    
    public String getGiftEndDateTime()
    {
        if (isGift)
            return giftEndDate + " 00:00:00";
        else if (!Validates.isEmpty(user.getEndDate()))
            return user.getEndDate() + " 00:00:00";
        else
            return getExpireInTime();
    }
    
    public void setGiftEndDate(String giftEndDate)
    {
        this.giftEndDate = giftEndDate;
    }
    
    public String getGiftVersionDesc() throws Exception
    {
        String desc = null;
        SysArticle article = ArticleDao.item(getGiftVersionNo());
        if (article == null)
            desc = "临时版";
        else
            desc = article.getItemName();
        return desc;
    }
    
    public String getSubNick()
    {
        return subNick;
    }

    public void setSubNick(String subNick)
    {
        this.subNick = subNick;
    }

    public String getSubSessionId()
    {
        return subSessionId;
    }

    public void setSubSessionId(String subSessionId)
    {
        this.subSessionId = subSessionId;
    }

    public String getSubSessionTime()
    {
        return subSessionTime;
    }

    public void setSubSessionTime(String subSessionTime)
    {
        this.subSessionTime = subSessionTime;
    }

    public int getSubExpiresIn()
    {
        return subExpiresIn;
    }

    public void setSubExpiresIn(int subExpiresIn)
    {
        this.subExpiresIn = subExpiresIn;
    }

    public int getSubExpiresInW2()
    {
        return subExpiresInW2;
    }

    public void setSubExpiresInW2(int subExpiresInW2)
    {
        this.subExpiresInW2 = subExpiresInW2;
    }

    /** 以下为客户淘宝信息 */
    public SellerCatRoot getSeRoot()
    {
        if (seRoot == null)
            service.buildUserSellerCat(this);
        
        return seRoot;
    }
    
    public void setSeRoot(SellerCatRoot seRoot)
    {
        this.seRoot = seRoot;
    }

    public String getHourString()
    {
        int hour = DateTimes.getCurrentHour();
        switch (hour)
        {
        case 0:case 1:case 2:case 3:case 4:case 5: return "凌晨好";
        case 6:case 7: return "早上好";
        case 8:case 9:case 10:case 11: return "上午好";
        case 12:case 13: return "中午好";
        case 14:case 15:case 16:case 17: return "下午好";
        case 18:case 19:case 20:case 21:case 22:case 23: return "晚上好";
        default: return "您好";
        }
    }
    
    public String getVersionDesc() throws Exception
    {
        SysArticle article = ArticleDao.item(user.getVersionNo());
        if (article == null)
            return "临时版";
        else
            return article.getItemName();
    }
    
    public String getExpireInTime()
    {
       String sessionTime = user.getSessionTime();
        int seconds =  user.getExpiresIn();
        String dateTime = DateTimes.getNextDateTimeStringBySecond(sessionTime, seconds);
        return dateTime;
    }
    
    public int getExpireDayNum()
    {
        String endDate = getGiftEndDate();
        String curDate = DateTimes.getDateString();
        return DateTimes.compareDay(endDate, curDate) - 1;
    }
    
    public String getShopUrl()
    {
        return "http://shop" + getShopId() + ".taobao.com";
    }
    
    public String getShopPic()
    {
        String shopPic = user.getShopPic();
        if (Validates.isEmpty(shopPic))
            return "/zres/shop_no_pic.gif";
        else
            return "http://logo.taobao.com/shop-logo"+shopPic;
    }
    
    public String getLevelDesc()
    {
       return getLevel(user.getLevel());
    }

    public String getLevel(int level)
    {
        String urlPre = "http://pics.taobaocdn.com/newrank/";
        switch (level)
        {
        case 1: return urlPre + "s_red_1.gif";
        case 2: return urlPre + "s_red_2.gif";
        case 3: return urlPre + "s_red_3.gif";
        case 4: return urlPre + "s_red_4.gif";
        case 5: return urlPre + "s_red_5.gif";
        case 6: return urlPre + "s_blue_1.gif";
        case 7: return urlPre + "s_blue_2.gif";
        case 8: return urlPre + "s_blue_3.gif";
        case 9: return urlPre + "s_blue_4.gif";
        case 10: return urlPre + "s_blue_5.gif";
        case 11: return urlPre + "s_cap_1.gif";
        case 12: return urlPre + "s_cap_2.gif";
        case 13: return urlPre + "s_cap_3.gif";
        case 14: return urlPre + "s_cap_4.gif";
        case 15: return urlPre + "s_cap_5.gif";
        case 16: return urlPre + "s_crown_1.gif";
        case 17: return urlPre + "s_crown_2.gif";
        case 18: return urlPre + "s_crown_3.gif";
        case 19: return urlPre + "s_crown_4.gif";
        case 20: return urlPre + "s_crown_5.gif";
        default: return "/ztmpl/res/s_red_0.gif";
        }
    }
        
    public int getFrom()
    {
        return from;
    }

    public void setFrom(int from)
    {
        this.from = from;
    }

    public boolean isWebLogin()
    {
        return from == 0;
    }
    
    public boolean isPcLogin()
    {
        return from == 1;
    }
    
    public boolean isMobileLogin()
    {
        return from == 2;
    }
    
    public boolean isHasSubNick()
    {
        return hasSubNick;
    }

    public void setHasSubNick(boolean hasSubNick)
    {
        this.hasSubNick = hasSubNick;
    }

    public List<SysArticle> getArticleList() throws Exception
    {
        return ArticleDao.list();
    }
    
    public String getItemName(int versionNo) throws Exception
    {
        SysArticle article = ArticleDao.item(versionNo);
        if (article == null)
            return "临时版";
        else
            return article.getItemName();
    }
    
    /***************************************************/
    //判断短授权
    /***************************************************/
    
    public boolean isAuthW2()
    {
        //判断授权时间
        String sessionTime = getSessionTime();
        String dateTime = TaobaoService.getToolService().getTaobaoTime();
        
        return (DateTimes.compareMinute(dateTime, sessionTime) < 25) && Math.abs(1800 - getExpiresInW2()) <= 1;
    }
    
    public long getAuthW2()
    {
        //判断授权时间
        if (getExpiresInW2() != 1800)
            return 0;
        
        long sessionTime = DateTimes.toDate(getSessionTime()).getTime() + 1800 * 1000;
        return sessionTime;
    }
    
    /***************************************************/
    //判断功能权限
    /***************************************************/
    
    public int getAppRuleByUrl(String appUrl) throws Exception
    {
        SysPermission permission = PermissionDao.itemPermissionByUrl(appUrl);
        if (permission == null)
            return 0;
        
        return permission.getPermissionRule();
    }
    
    public boolean isAppPermissionUrl(String appUrl) throws Exception
    {
        return PermissionDao.isAppPermissionUrl(appUrl, getGiftVersionNo(), getCreateTime());
    }
    
    public String getAppPermissionId(String appUrl) throws Exception
    {
        SysPermission permission = PermissionDao.itemPermissionByUrl(appUrl);
        if (permission == null)
            return null;
        
        return permission.getPermissionId();
    }
    
    /***************************************************/
    //弹出广告
    /***************************************************/
    
    public boolean isClosePopup()
    {
        return isClosePopup;
    }

    public void setClosePopup()
    {
        this.isClosePopup = true;
    }
    
    public SysPopup getPopup()
    {
        return popup;
    }
    
    public String getPopupHtml()
    {
        if (popup == null)
            return null;
        
        String html = popup.getPopupFtl();
        html = html.replaceAll("\r", "");
        html = html.replaceAll("\n", "");
        return html;
    }
    
    public boolean isPopup() throws Exception
    {
        if(isClosePopup)
            return false;
        
        //存在弹出条件的窗口
        if(popup != null)
            return true;
        
        Selector selector = new Selector("popupStatus", 1);
        selector.addOrderbyAsc("popupIndex");
        List<SysPopup> validPopupList = ORM.table().list(SysPopup.class, selector);
        //如果没有有效条件
        if(validPopupList==null || validPopupList.isEmpty())
            return false;
        
        int userVersion = getGiftVersionNo();//用户版本号
        int exprieDayNum = getExpireDayNum();//到期剩余天数
        
        for(SysPopup popup : validPopupList)
        {
            //版本不符合条件
            if(userVersion<popup.getLowestVersion() || userVersion>popup.getHighestVersion())
                continue;
            
            //到期不符合
            int expireDay = popup.getExpireDay();
            if(expireDay>0 && exprieDayNum>expireDay)
                continue;
            
            //弹出窗口类型与登录版本一致
            if(isWebLogin() && popup.getPopupType() == 0)
            {
                this.popup = popup;
                return true;
            }
            else if(isPcLogin() && popup.getPopupType() == 1)
            {
                this.popup = popup;
                return true;
            }
        }
        
        return false;
    }
    
    /***************************************************/
    //顶部通知
    /***************************************************/
    
    public boolean isCloseTopNotice()
    {
        return isCloseTopNotice;
    }

    public void setCloseTopNotice()
    {
        this.isCloseTopNotice = true;
    }
    
    public boolean isTopNotice() throws ORMException, SQLException
    {
        if (!SysParamDao.isTrue("portal.notice", "is"))
            return false;
        
        int version = SysParamDao.getInt("portal.notice", "version");
        return getGiftVersionNo() <= version && !isCloseTopNotice;
    }
    
    /***************************************************/
    //是否管理员
    /***************************************************/
    
    public boolean isAdmin()
    {
        return isAdmin;
    }

    public void setAdmin(boolean isAdmin)
    {
        this.isAdmin = isAdmin;
    }

    /***************************************************/
    //是否已更新数据，在/refresh.htm中用到
    /***************************************************/
    
    public boolean isUpdateData()
    {
        return isUpdateData;
    }

    public void setUpdateData(boolean isUpdateData)
    {
        this.isUpdateData = isUpdateData;
    }

    /***************************************************/
    //是否功能测试用户
    /***************************************************/
    public boolean isTestFunctionNick()
    {
        String nickstr = Global.getString("project", "testFunctionNick");
        if (Validates.isEmpty(nickstr))
            return false;
        
        String nick = getNick();
        String[] nicks = nickstr.split(",");
        for (String n : nicks)
        {
            if (nick.equals(n))
                return true;
        }

        return false;
    }

    
    public long getOpenAppKey() {
        return open_app_key;
    }

    public void setOpenAppKey(long open_app_key) {
        this.open_app_key = open_app_key;
    }
    public boolean isLoginOpenApp() {
        return open_app_key > 0;
    }
    /***************************************************/
    //最低折扣
    /***************************************************/
    
    public String getLowestDiscount()
    {
        return (Validates.isEmpty(user.getLowestDiscount()))?"7.00":user.getLowestDiscount();
    }
    
    public void setLowestDiscount(String lowestDiscount)
    {
        this.user.setLowestDiscount(lowestDiscount);
    }
    
    /***************************************************/
    //从数据库中刷新用户
    /***************************************************/
    
    public void doRefreshUserInfo()
    {
        service.doRefreshUserInfo(this);
    }
    
    /***************************************************/
    //保留以前遗留的功能
    /***************************************************/
    
    /** 请使用removeValue(String key)方法代替 */
    @Deprecated
    public void setValueClean(String key)
    {
        removeValue(key);
    }
}
